package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.*;
import com.mbyte.easy.admin.mapper.GroupMapper;
import com.mbyte.easy.admin.mapper.VideoMapper;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.DraftLogConstant;
import com.mbyte.easy.common.constant.StatusRecordVideo;
import com.mbyte.easy.common.constant.StatusWriter;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.util.DateUtil;
import com.mbyte.easy.util.OssUtil;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Controller
@RequestMapping("/admin/sectionVideo")
public class VideoSectionController extends BaseController{
    private String prefix = "admin/video/video/";

    @Autowired
    private IVideoService videoService;
    @Autowired
    private IPptService pptService;
     @Autowired
    private IUserService userService;

     @Autowired
     private VideoMapper videoMapper;
     @Autowired
    IRelationService relationService;
     @Autowired
    IDraftService draftService;
     @Autowired
     private GroupMapper groupMapper;
     @Autowired
    private IGroupService groupService;
     @Autowired
     private  ICheckService checkService;
         @Autowired
    private ApplicationEventPublisher applicationEventPublisher;



    /**
     * @Author  刘辉
     * @Description 录屏课程对接人--待审核录屏
     * @Date 2020年2月29日
     * @Param
     * @return
     **/
    @RequestMapping("unviewedVideo")
    public String unviewedVideo(Model model,
                                @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                String submitTimeSpace, String allotTimeSpace,
                                String createTimeSpace, String updateTimeSpace,
                                Video video) {
        Page<Video> page = new Page<Video>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<Video>();
       if (!ObjectUtils.isEmpty(submitTimeSpace)){
           queryWrapper.between("tv.submit_time", DateUtil.getStart(submitTimeSpace)
                   ,DateUtil.getEnd(submitTimeSpace).plusDays(1));
        }
        //逆序
        queryWrapper.lambda().orderByDesc(Video::getUpdateTime);

        QueryWrapper<Relation> relationQueryWrapper = new QueryWrapper<>();
        Long aLong = pptService.selectIdByUsername(Utility.getCurrentUsername());
        //：：访问构造方法，静态方法，对象方法
        relationQueryWrapper.lambda().eq(Relation::getParentId, aLong);
        List<Relation> list = relationService.list(relationQueryWrapper);
        QueryWrapper<Draft> draftQueryWrapper = new QueryWrapper<>();
        if (list.size() != 0) {

                queryWrapper.eq("tv.status_code", StatusRecordVideo.STATUS_RECORD_PPTTORECORD_UPLOADTO);
                queryWrapper.eq("tv.draft_type", StatusRecordVideo.STATUS_VIDEO_RECORD_AUVEFINALLEADER_DRAFT_TYPE2);


               IPage<Video> pageInfo =videoMapper.listPagess(page,queryWrapper);

                model.addAttribute("submitTimeSpace", submitTimeSpace);
                model.addAttribute("searchInfo", video);
                model.addAttribute("pageInfo", new PageInfo(pageInfo));
                return prefix+"SectionLeaderUnviewed";
        } else {
            queryWrapper.lambda().eq(Video::getStatusCode, StatusWriter.ERROR);
            IPage<Video> pageInfo = videoService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderUnviewed";
        }
    }
    /**
     * @Author 牛英健  刘辉
     * @Description 录屏课程对接人--已通过录屏
     * @Date 2019年12月28日
     * @Param
     * @return
     **/
    @RequestMapping("successVideo")
    public String successVideo(Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String allotTimeSpace, String createTimeSpace, String updateTimeSpace, Video video) {
        Page<Video> page = new Page<Video>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<Video>();

        if (!ObjectUtils.isEmpty(submitTimeSpace)){
            queryWrapper.between("tv.submit_time", DateUtil.getStart(submitTimeSpace)
                    ,DateUtil.getEnd(submitTimeSpace).plusDays(1));
        }

        queryWrapper.lambda().orderByDesc(Video::getUpdateTime);

        SysUser sysUser = pptService.getUserByUserName(Utility.getCurrentUsername());
        List<Check> groupByUserId = pptService.getChecksById(sysUser.getId());

        if (groupByUserId.size()!=0){
            log.info("groupByUserId==============>>>>{}",groupByUserId);
            queryWrapper.in("tv.id", groupByUserId.stream().map(Check::getDraftId).collect(Collectors.toList()));
            queryWrapper.eq("tv.status_code",
                    StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_SUCCESS);//1028

            IPage<Video> pageInfo = videoMapper.listPagess(page,queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderSuccessReviewed";
        }else {
            queryWrapper.lambda().eq(Video::getStatusCode, StatusWriter.ERROR);
            IPage<Video> pageInfo = videoService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderSuccessReviewed";
        }
    }

    /**
     * @Author 牛英健 刘辉
     * @Description 录屏课程对接人--已驳回录屏处理
     * @Date 2019年12月28日
     **/
    @RequestMapping("failedVideo")
    public String failedVideo(Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String allotTimeSpace, String createTimeSpace, String updateTimeSpace, Video video) {
        Page<Video> page = new Page<Video>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<Video>();
       if (!ObjectUtils.isEmpty(submitTimeSpace)){
           queryWrapper.between("tv.submit_time", DateUtil.getStart(submitTimeSpace)
                   ,DateUtil.getEnd(submitTimeSpace).plusDays(1));
        }
        queryWrapper.lambda().orderByDesc(Video::getUpdateTime);
        SysUser sysUser = pptService.getUserByUserName(Utility.getCurrentUsername());
        List<Check> groupByUserId = pptService.getChecksByIdUnPass(sysUser.getId());

        if(groupByUserId.size()!=0){

            queryWrapper.in("tv.id", groupByUserId.stream().map(Check::getDraftId).collect(Collectors.toList()));
            queryWrapper.eq("tv.status_code", StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED);

            IPage<Video> pageInfo = videoMapper.listPagess(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderFailedReviewed";
        }else{
            queryWrapper.lambda().eq(Video::getStatusCode, StatusWriter.ERROR);
            IPage<Video> pageInfo = videoService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderFailedReviewed";
        }
    }
    /**
     * @Author 牛英健 刘辉
     * @Description 录屏课程对接人--被驳回录屏
     * @Date 2019年12月28日
     * @Param
     * @return
     **/
    @RequestMapping("beFailedVideo")
    public String beFailedVideo(Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String submitTimeSpace, String allotTimeSpace, String createTimeSpace, String updateTimeSpace, Video video) {
        Page<Video> page = new Page<Video>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<Video>();
        if (!ObjectUtils.isEmpty(submitTimeSpace)){
            queryWrapper.between("tv.submit_time", DateUtil.getStart(submitTimeSpace)
                    ,DateUtil.getEnd(submitTimeSpace).plusDays(1));
        }

        queryWrapper.lambda().orderByDesc(Video::getUpdateTime);
        SysUser sysUser = pptService.getUserByUserName(Utility.getCurrentUsername());
        List<Check> groupByUserId = pptService.getChecksByIdPass(sysUser.getId());
        if(groupByUserId.size()!=0){
            queryWrapper.in("tv.id", groupByUserId.stream().map(Check::getDraftId).collect(Collectors.toList()));
            log.info("===groupByUserId==={}",groupByUserId);
            queryWrapper.in("tv.status_code",
                    StatusRecordVideo.STATUS_RECORD_FUNCTIONARY_FAILED);//2029
            IPage<Video> pageInfo = videoMapper.listPagess(page, queryWrapper);


            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderBeFailed";
        }else{
            queryWrapper.lambda().eq(Video::getStatusCode, StatusWriter.ERROR);
            IPage<Video> pageInfo = videoService.page(page, queryWrapper);
            model.addAttribute("submitTimeSpace", submitTimeSpace);
            model.addAttribute("searchInfo", video);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"SectionLeaderBeFailed";
        }
    }

    /**
     * oss 文件下载
     * @param videoId ppt主键
     */
    @PostMapping(value = "ossDownloadFile",produces="application/json")
    public void downloadFile(@RequestParam("videoId") String videoId, HttpServletResponse response) {
        log.info("pptId===================== "+videoId);

        String  path = videoService.getById(Long.valueOf(videoId)).getVideoUrl();
        log.info("path===================== "+path);
        log.info("开始文件下载===================== ");
        OssUtil.download2FileByStream(path,response);
    }

    /**
     * @Author 牛英健 刘辉
     * @date 2019年12月23日17:53:04
     * 2月10日改
     * 录屏课程对接人--单个通过
     * @return
     */
    @GetMapping("successById")
    @ResponseBody
    public AjaxResult successById(@RequestParam("id") Long id,
                                  String draftTitle,
                               String draftText,
                               Long draftNum,
                               String fileName) {
        log.info("========================>{}", draftTitle);
        log.info("========================>{}", draftText);
        log.info("========================>{}", draftNum);
        log.info("========================>{}", fileName);

        Draft draft = draftService.getById(videoService.getById(id).getDraftId());
        draft.setDraftText(draftText);
        draft.setDraftTitle(draftTitle);
        draft.setDraftNum(draftNum);
        draft.setFileName(fileName);
        draftService.updateById(draft);

        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        Video video = new Video();
        video.setStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_SUCCESS);
        video.setLastOperator(pptService.selectIdByUsername(Utility.getCurrentUsername()));
        queryWrapper.in("id", id);
        videoService.update(video, queryWrapper);

        //更新分组的userId
        String username = Utility.getCurrentUsername();
        SysUser sysUser = draftService.getUserIdByUserName(username);
        Group group =new Group();
        group.setGroupId(videoMapper.selectById(id).getGroupId());
        group.setUserId(sysUser.getId());
        groupMapper.updateByGroupId(group);


        Check check = new Check();
        check.setIsPass(false);
        check.setPreStatusCode(StatusRecordVideo.STATUS_RECORD_PPTTORECORD_UPLOADTO);//1027
        check.setOverStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_SUCCESS);
        check.setUserId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        //check表draft插入PPT表的id
        check.setDraftId(id);
        pptService.insertCheck(check);

        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_CHECK_YES)
                    .setDraftId((videoService.getById(id).getDraftId()))
                    .setGroupId(videoMapper.selectById(id).getGroupId())
                    .setActionContent("录屏课程对接人通过录屏")
                    .setPrimaryState(StatusRecordVideo.STATUS_RECORD_PPTTORECORD_UPLOADTO)
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_SUCCESS));

        return toAjax(true);
    }
    /**
     * @param
     * @return
     * @author 牛英健  刘辉
     * @date 2019年12月16日16:47:28
     * 录屏课程对接人
     * 获取 拒绝 id
     */
    @GetMapping("failedBefore/{id}")
    public String failedAll(@PathVariable("id") Long id, Model model) {
        log.info("===========failedBefore=============>{}", id);
        model.addAttribute("id", id);
        return prefix + "SectionLeaderFailedReason";
    }

    /**
     * @param
     * @return
     * @author 牛英健   刘辉
     * @date 2019年12月16日16:47:28
     * 录屏课程对接人
     * 拒绝
     */
    @PostMapping("SectionLeaderFailedReason")
    @ResponseBody
    public AjaxResult SectionLeaderFailedReason(Long id, String reason,String draftText,Long status,
                                                String draftTitle,Long draftNum,String fileName) {
        log.info("=======SectionLeaderFailedReason==========>{}", id);
        log.info("========================>{}", reason);

        Draft draft = draftService.getById(videoService.getById(id).getDraftId());
        draft.setDraftText(draftText);
        draft.setDraftTitle(draftTitle);
        draft.setDraftNum(draftNum);
        draft.setFileName(fileName);
        draftService.updateById(draft);

        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        Video video = new Video();
        video.setStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED);
        video.setLastOperator(pptService.selectIdByUsername(Utility.getCurrentUsername()));
        queryWrapper.in("id", id);
        videoService.update(video, queryWrapper);

        Check check = new Check();
        check.setIsPass(true);
        check.setPreStatusCode(StatusRecordVideo.STATUS_RECORD_PPTTORECORD_UPLOADTO);
        check.setOverStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED);
        check.setUserId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        check.setDraftId(id);
        check.setCreateTime(LocalDateTime.now());
        check.setReason(reason);
        pptService.insertCheck(check);
        if (status==1027){
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_CHECK_NO)
                    .setDraftId(videoService.getById(id).getDraftId())
                    .setGroupId(videoService.getById(id).getGroupId())
                    .setPrimaryState(StatusRecordVideo.STATUS_RECORD_PPTTORECORD_UPLOADTO)
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED)
                    .setReason(reason));
        }else {
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_CHECK_NO)
                    .setDraftId(videoService.getById(id).getDraftId())
                    .setGroupId(videoService.getById(id).getGroupId())
                    .setPrimaryState(StatusRecordVideo.STATUS_RECORD_FUNCTIONARY_FAILED)
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED)
                    .setReason(reason));
        }

        return AjaxResult.success();
    }

       /**
     * @param
     * @return
     * @author 刘辉
     * @date 2019年12月16日16:47:28
     * 课程校对人----拒绝
     */
    @PostMapping("refusePPTVideo")
    @ResponseBody
    public AjaxResult refusePPTVideo(Long id, String reason,String draftTitle,String draftText,Long draftNum,String fileName) {
        log.info("=======视频表的id==========>{}", id);
        log.info("========================>{}", reason);

        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        Video video = new Video();
        video.setStatusCode(StatusRecordVideo.STATUS_RECORD_COURSEREADER_FAILED);
        video.setLastOperator(pptService.selectIdByUsername(Utility.getCurrentUsername()));
        queryWrapper.in("id", id);
        videoService.update(video, queryWrapper);

        Draft draft = draftService.getById(videoService.getById(id).getDraftId());
        draft.setDraftText(draftText);
        draft.setDraftTitle(draftTitle);
        draft.setDraftNum(draftNum);
        draft.setFileName(fileName);
        draftService.updateById(draft);

        Check check = new Check();
        check.setIsPass(true);
        check.setPreStatusCode(StatusRecordVideo.STATUS_RECORD_AUVELEADER_DISTRIBUTION);
        check.setOverStatusCode(StatusRecordVideo.STATUS_RECORD_COURSEREADER_FAILED);
        check.setUserId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        check.setDraftId(videoService.getById(id).getDraftId());
        check.setCreateTime(LocalDateTime.now());
        check.setReason(reason);
        checkService.save(check);


        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_CHECK_NO)
                    .setDraftId(videoService.getById(id).getDraftId())
                    .setGroupId(videoService.getById(id).getGroupId())
                    .setPrimaryState(StatusRecordVideo.STATUS_RECORD_AUVELEADER_DISTRIBUTION)
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_COURSEREADER_FAILED)
                    .setReason(reason));

        return AjaxResult.success();
    }


    /**
     * @param
     * @return
     * @author 牛英健
     * @date 2019年12月16日16:47:28
     * 录屏课程对接人 --查看驳回理由
     * PPT
     */
    @GetMapping("failedReasonBefore/{id}")
    public String failedReasonBefore(@PathVariable("id") Long id, Model model) {
        List<Check> checkById = pptService.getCheckById(id);
        log.info("checkById==================>>{}",checkById);
        log.info("当前登录人：==============>>{}",pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        log.info("true Or false???>>>>>>{}",pptService.getUserByUserName(Utility.getCurrentUsername()).getId()==checkById.get(0).getUserId());
        for (int i = 0; i < checkById.size(); i++) {
            if (pptService.getUserByUserName(Utility.getCurrentUsername()).getId()==checkById.get(i).getUserId()
                    &&checkById.get(i).getIsPass()==true
            &&checkById.get(i).getOverStatusCode().equals(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_FAILED)){
                model.addAttribute("check", checkById.get(i).getReason());
                return prefix + "FailedReasonBefore";
            }
        }
        return prefix + "FailedReasonBefore";
    }
    /**
     * @param
     * @return
     * @author 孙祺至
     * @date 2019年12月16日16:47:28
     * 板块负责人查看被驳回理由
     * PPT
     */
    @GetMapping("BefailedReasonBefore/{id}")
    public String BefailedReasonBefore(@PathVariable("id") Long id, Model model) {
        List<Check> checkById = pptService.getCheckById(id);

        for (int i = 0; i < checkById.size(); i++) {
            if (videoService.getById(id).getLastOperator()==checkById.get(i).getUserId()
                    &&checkById.get(i).getIsPass()==true){
                model.addAttribute("check", checkById.get(i).getReason());
                return prefix + "FailedReasonBefore";
            }
        }
        return prefix + "FailedReasonBefore";
    }
}
